<template>
  <view class="u-page">
    <view class="userbjInfo" v-if="userInfo">
      <view>
        <view class="uname">{{userInfo.userName}}</view>
        <view class="ugd">{{userInfo.ssgd}}</view>
      </view>
      <view class="jilu" @click='toJl'>
        <u-icon name="order" color="#4b4d4e" size="28"></u-icon>
        <view class="jl">打卡记录</view>
      </view>
      <!-- <span class="bj">{{userInfo.className}}</span> -->
    </view>

    <view class="qiandaoArea">
        <view class="now">打卡时间：{{ dateStr }}</view>
      <view class="bigbtn" v-if='dzhi' @click="doDaka">
        <view class="paizhao"> </view>
        <view class="wydk">拍照打卡</view>
      </view>
      <view class="bigbtn disabled " v-else>
        <view class="paizhao"> </view>
        <view class="wydk">拍照打卡</view>
      </view>

      <view class="position">
        <!-- <template v-if="inRadius"
          ><u-icon name="map-fill" color="#73D29F" size="18"></u-icon
          >已进入考勤范围：{{ kqfw.name }}</template
        >
        <template v-else
          ><u-icon name="map-fill" color="#DF1111" size="18"></u-icon
          >未进入考勤范围：{{ kqfw.name }}</template
        > -->
        <template
          ><u-icon name="map-fill" color="#73D29F" size="18"></u-icon
          >{{ dzhi }}</template
        >
      </view>

      <!-- <view class="test">
        {{ lnglat }} / {{ distance }} <view></view> {{ kqfw.center }} /
        {{ kqfw.radius }}
      </view> -->
    </view>
    <mytabbar v-if="characterType"></mytabbar>
  </view>
</template>
<script>
import getLocation from "@/utils/getLocation.js";
import { mapState, mapMutations } from "vuex";
import mathUtil from "@/utils/mathUtil.js";
import sceneMixins from "@/utils/sceneMixins";
import mytabbar from "@/components/tabbar/index.vue";
import { uniqBy } from "lodash";
export default {
  options: { styleIsolation: "shared" },
  components: { mytabbar: mytabbar },
  mixins: [getLocation, sceneMixins],
  computed: {
    ...mapState([
      "lnglat",
      "userInfo",
      "openId",
      "characterType",
      "globalConfig",
    ]),
  },
  data() {
    return {
      dateStr: this.$Util.getFmtDate(new Date()),
      qd: "",
      qt: "",
      currentEvent: "",
      kqfw: "",
      inRadius: false,
      distance: 0,
      dzhi: "",
    };
  },
  filters: {},
  methods: {
    ...mapMutations(["changeTab", "changeCharacterType"]),
    getMinutes: function (str) {
      var h = parseInt(str.split(":")[0]);
      var m = parseInt(str.split(":")[1]);
      return h * 60 + m;
    },
    toJl:function(){
              uni.navigateTo({
          url: '/pages/content/list?loadJSON=/mobile/qyjg/wxJSON/打卡记录/list.json',
        });
    },
    doDaka: function () {
      var vm = this;

      if (!vm.lnglat) {
        uni.showModal({
          title: "提示",
          content: "获取定位失败，请检查定位服务和定位权限是否打开",
          showCancel: false,
          success: function (res2) {
            clearInterval(this);
            uni.switchTab({
              url: "/pages/index/index",
            });
          },
        });
      }
      //正式打卡操作（人脸识别 新版）
      // wx.startFacialRecognitionVerify({
      //   name: vm.userInfo.userName,
      //   idCardNumber: vm.userInfo.idCard,
      //   complete: function (res) {
      //     if (res.errCode == 0) {
      //       //认证成功操作

      //       vm.getAndLoad(
      //         "获取打卡结果",
      //         vm.WX_ASSETS +
      //           "/user/saveSignin.jsp?" +
      //           vm.$Util.stringify({
      //             type: vm.userInfo.superviseType,
      //             whetherPunitive: vm.userInfo.whetherPunitive,
      //             userName: vm.userInfo.userName,
      //             idCard: vm.userInfo.idCard,
      //             addr: vm.dzhi,
      //             addrLng: vm.lnglat[1],
      //             addrLat: vm.lnglat[0],
      //             // signinTime: vm.$Util.getFmtDate(
      //             //   new Date(),
      //             //   "yyyy-MM-dd hh:mm:ss"
      //             // ),
      //           }),
      //         function (res) {
      //           if (res.code == 0) {
      //             uni.showModal({
      //               title: "提示",
      //               content: "打卡成功",
      //               showCancel: false,
      //               success: function (res3) {
      //                 uni.navigateBack();
      //               },
      //             });
      //           } else {
      //             uni.showModal({
      //               title: "提示",
      //               content: "打卡失败",
      //               showCancel: false,
      //               success: function (res4) {},
      //             });
      //           }
      //         }
      //       );
      //     }
      //   },
      // });

      uni.chooseImage({
        sizeType: ["compressed"], //original 原图，compressed 压缩图，默认二者都有
        sourceType: ["album", "camera"], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
        success: (res) => {
          var url = res.tempFilePaths[0];
          vm.uploadFile(url, (res) => {
            if (res.code == 0) {
              var src=res.data.src
              vm.getAndLoad(
                "获取打卡结果",
                vm.WX_ASSETS +
                  "/xcx/record/save.jsp?" +
                  vm.$Util.stringify({
                    // type: vm.userInfo.superviseType,
                    // whetherPunitive: vm.userInfo.whetherPunitive,
                    // userName: vm.userInfo.userName,
                    // idCard: vm.userInfo.idCard,
                    // addr: vm.dzhi,
                    // addrLng: vm.lnglat[1],
                    // addrLat: vm.lnglat[0],
                    place:vm.dzhi,
                    attach:src,
                    createTime: vm.$Util.getFmtDate(
                      new Date(),
                      "yyyy-MM-dd hh:mm:ss"
                    ),
                  }),
                function (res) {
                  if (res.code == 0) {
                    uni.showModal({
                      title: "提示",
                      content: "打卡成功",
                      showCancel: false,
                      success: function (res3) {
                        // uni.navigateBack();
                      vm.changeTab(0);
        uni.switchTab({
          url: '/pages/index/index',
        });
                      },
                    });
                  } else {
                    uni.showModal({
                      title: "提示",
                      content: "打卡失败",
                      showCancel: false,
                      success: function (res4) {},
                    });
                  }
                }
              );
            } else {
              uni.$u.toast("上传失败");
            }
          });
        },
      });
    },
    updateQdQtObject: function () {
      var vm = this;
      vm.qdqtTimeout && clearTimeout(vm.qdqtTimeout);
      var currentM = vm.getMinutes(vm.$Util.getFmtDate(new Date(), "hh:mm"));
      if (vm.qd.did) {
        vm.qd.status = 1;
        vm.qd.showText = "已打卡 " + vm.qd.reportTime;
      } else {
        let status = 0;
        let showText = "";
        let startM = vm.getMinutes(vm.qd.startTime);
        let endM = vm.getMinutes(vm.qd.endTime);
        if (currentM < startM) {
          // 未打卡 判断有没有开始
          status = -1;
          showText = "未到打卡时间";
        } else if (currentM > endM) {
          status = 2;
          showText = "缺卡";
        }
        vm.qd.status = status;
        vm.qd.showText = showText;
      }

      if (vm.qt.did) {
        vm.qt.status = 1;
        vm.qt.showText = "已打卡 " + vm.qt.reportTime;
      } else {
        let status = 0;
        let showText = "";
        let startM = vm.getMinutes(vm.qt.startTime);
        let endM = vm.getMinutes(vm.qt.endTime);
        if (currentM < startM) {
          // 未打卡 判断有没有开始
          status = -1;
          showText = "未到打卡时间";
        } else if (currentM > endM) {
          status = 2;
          showText = "缺卡";
        }
        vm.qt.status = status;
        vm.qt.showText = showText;
      }

      if (vm.qd.status == 0) {
        vm.currentEvent = vm.qd;
      } else {
        vm.currentEvent = vm.qt;
      }
      // 10秒后刷新一下状态
      vm.qdqtTimeout = setTimeout(() => {
        vm.updateQdQtObject();
      }, 10 * 1000);
    },
    stopUpdateLocation: function () {
      uni.setKeepScreenOn({ keepScreenOn: false });
      clearInterval(global.hymGjsbInterval);
      return this.stopListenUserLocation();
    },

    calculateDistance: function () {
      var vm = this;
      if (vm.kqfw && vm.lnglat) {
        var distance = mathUtil.getDistance(
          vm.lnglat[1],
          vm.lnglat[0],
          vm.kqfw.center[1],
          vm.kqfw.center[0]
        );
        vm.inRadius = distance <= vm.kqfw.radius;
        vm.distance = distance;
      }
    },

    logPosition() {
      var vm = this;
      vm.getUserLocation().then((res) => {
        vm.setPosition(res);
        vm.calculateDistance();
      });
    },
    logPosition2(res) {
      var vm = this;
      vm.setPosition(res);
      if (vm.kqfw) {
        vm.calculateDistance();
      }
    },
  },
  onShow() {
    var vm = this;
    if (vm.uploadByListen) {
      vm.listenUserLocation(vm.logPosition2, false);
    } else {
      vm.logPosition();
      global.hymGjsbInterval = setInterval(() => {
        vm.logPosition();
      }, 15000);
    }
    uni.showLoading({ title: "正在获取定位" });
    vm.failTime = 0;

      if (vm.lnglat) {
        var wz = "";
        wz = vm.lnglat[1] + "," + vm.lnglat[0];
        uni.hideLoading();

        wx.request({
          url: "https://apis.map.qq.com/ws/geocoder/v1/",
          method: "GET",
          data: {
            location: wz,
            key: "RTXBZ-JO3HJ-GS5FQ-XGEE6-YA47V-HABPC",
          },
          success: (res) => {
            vm.dzhi = res.data.result.address;
          },
        });
      }
    
  },
  onLoad(options) {
    var vm = this;
    vm.waitVariable("token").then(() => {
      // var taskType = options.taskType;
      vm.dateStr2 = vm.dateStr.replace(/-/g, "/") + " ";
      vm.uploadByListen = wx.canIUse("startLocationUpdate");
    });
  },
  destroyed() {
    this.qdqtTimeout && clearTimeout(this.qdqtTimeout);
    clearTimeout(global.reloadInfoTimeout);
    this.stopUpdateLocation();
  },
};
</script>

<style lang="scss" scoped>
.u-page {
  height: 100vh;
  overflow-y: scroll;
}
.userbjInfo {
  // background: #fff;

  background: #fff;
  background-size: 100% 100%;
  height: 120rpx;
  padding: 30rpx;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .name {
    font-size: 18px;
    font-weight: bold;
    display: inline-block;
    color: #000;
  }
  .bj {
    color: #3069ab;
    font-size: 14px;
    margin-left: 5px;
  }
  .date {
    margin-left: auto;
  }
  .uname{
    font-size: 32rpx;
    font-weight: bold;
    color: #000;
  }
  .ugd{
    font-size: 28rpx;
    color: #727374;
  }
  .jilu{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .jl{
      font-size: 20rpx;
      color: #4b4d4e
    }
  }
}
.qiandaoArea {
  background: #fff;
  border-radius: 20rpx;
  margin: 20rpx 30rpx;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  .now{
   width: 80%;
	height: 90rpx;
  line-height: 90rpx;
  background-color: #d9e7f5;
  border-radius: 20rpx;
	border: solid 2rpx #4ba8eb;
  font-size: 30rpx;
  color: #1b7fe2;
  text-align: center;
  }
  .legends {
    display: flex;
    .item {
      background: #ededee;
      border-radius: 10rpx;
      padding: 20rpx;
      display: flex;
      flex-direction: column;
      flex: 1;
      margin: 0 10rpx 0 10rpx;
      box-sizing: border-box;
      &.active {
        border: 1px solid #5bc68d;
      }
      .status {
        color: #999999;
        font-size: 26rpx;
        margin-top: 10rpx;
      }
    }
  }
  .bigbtn {
    width: 490rpx;
    height: 490rpx;
    background: linear-gradient(
      45deg,
      rgba(94, 163, 241, 0.9),
      rgba(94, 163, 241, 0.7)
    );
    // background: url("#{$APIPATH}#{$WX_IMAGES}/wxAssets/wxImages/dkbtn.png")
    //   no-repeat;
    background-size: 100% 100%;
    border-radius: 50%;
    color: #fff;
    font-size: 34rpx;
    letter-spacing: 5rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 100rpx auto;
    &.disabled {
      background: linear-gradient(45deg, #bdb7b7, #d8d0d0);
    }
    .paizhao {
      width: 115rpx;
      height: 91rpx;
      background: url("#{$WXIMAGES}/paizhao.png");
      background-size: 100% 100%;
    }
    .wydk {
      width: 100%;
      text-align: center;
      margin-top: 90rpx;
    }
  }
  .position {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: #999999;
    margin: 0 60rpx;
    padding-bottom: 60rpx;
  }
}
</style>
